<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人信息管理 - 管理后台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar-transition {
            transition: transform 0.3s ease-in-out;
        }
        .sidebar-overlay {
            transition: opacity 0.3s ease-in-out;
        }
    </style>
</head>

<body class="bg-gray-50">
    <!-- 顶部导航栏 -->
    <nav class="bg-white shadow-sm border-b border-gray-200 fixed top-0 left-0 right-0 z-40">
        <div class="px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <button id="sidebarToggle" class="lg:hidden p-2 rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <i class="fas fa-bars"></i>
                    </button>
                    <div class="flex-shrink-0 flex items-center ml-4 lg:ml-0">
                        <i class="fas fa-code text-blue-600 text-xl mr-3"></i>
                        <h1 class="text-xl font-bold text-gray-900">个人信息管理</h1>
                    </div>
                </div>
                
                <div class="flex items-center space-x-4">
                    <div id="userControls" class="flex items-center space-x-4">
                        <!-- 用户控件将通过 JavaScript 动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <aside id="sidebar" class="fixed inset-y-0 left-0 z-30 w-64 bg-white shadow-lg transform -translate-x-full lg:translate-x-0 sidebar-transition">
        <div class="flex items-center justify-center h-16 px-4 bg-blue-600">
            <i class="fas fa-cogs text-white text-2xl"></i>
            <span class="ml-3 text-white font-semibold text-lg">管理后台</span>
        </div>
        
        <nav class="mt-8 px-4">
            <ul class="space-y-2">
                <li>
                    <a href="/" class="flex items-center px-4 py-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fas fa-home w-5 h-5 mr-3"></i>
                        <span>首页</span>
                    </a>
                </li>
                <li>
                    <a href="/files" class="flex items-center px-4 py-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fas fa-folder w-5 h-5 mr-3"></i>
                        <span>文件管理</span>
                    </a>
                </li>
                <li>
                    <a href="/profile" class="flex items-center px-4 py-3 text-gray-700 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors">
                        <i class="fas fa-user w-5 h-5 mr-3"></i>
                        <span>个人信息</span>
                    </a>
                </li>
                <li class="pt-4 mt-4 border-t border-gray-200">
                    <a href="https://gitee.com/lineuman/lcs_flask_claude" target="_blank" class="flex items-center px-4 py-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fab fa-git w-5 h-5 mr-3"></i>
                        <span>源码</span>
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 侧边栏遮罩 -->
    <div id="sidebarOverlay" class="fixed inset-0 bg-black bg-opacity-50 z-20 lg:hidden sidebar-overlay opacity-0 pointer-events-none"></div>

    <!-- 主内容区域 -->
    <div class="lg:ml-64 pt-16">
        <div class="p-4 sm:p-6 lg:p-8">
        <!-- 警告消息 -->
        <div id="alert" class="hidden mb-4 p-4 rounded-md"></div>
        
        <!-- 用户信息管理表单 -->
        <div class="bg-white shadow-md rounded-lg p-6 mb-6">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold">个人信息管理</h2>
                <a href="/" class="text-blue-500 hover:text-blue-700">
                    <i class="fas fa-arrow-left mr-1"></i>返回首页
                </a>
            </div>
            
            <form id="profileForm">
                <!-- 基本信息 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                        <input type="text" id="username" name="username" readonly
                               class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-500">
                        <p class="text-xs text-gray-500 mt-1">用户名不可修改</p>
                    </div>
                    
                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                        <input type="email" id="email" name="email" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label for="full_name" class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
                        <input type="text" id="full_name" name="full_name" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">电话</label>
                        <input type="tel" id="phone" name="phone" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <!-- 头像URL -->
                <div class="mb-6">
                    <label for="avatar_url" class="block text-sm font-medium text-gray-700 mb-2">头像URL</label>
                    <input type="url" id="avatar_url" name="avatar_url" 
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <p class="text-xs text-gray-500 mt-1">输入头像图片的URL地址</p>
                </div>
                
                <!-- 个人简介 -->
                <div class="mb-6">
                    <label for="bio" class="block text-sm font-medium text-gray-700 mb-2">个人简介</label>
                    <textarea id="bio" name="bio" rows="4" 
                              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                              placeholder="介绍一下你自己..."></textarea>
                </div>
                
                <!-- 密码修改 -->
                <div class="border-t pt-6">
                    <h3 class="text-lg font-semibold mb-4">修改密码</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="current_password" class="block text-sm font-medium text-gray-700 mb-2">当前密码</label>
                            <input type="password" id="current_password" name="current_password" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label for="new_password" class="block text-sm font-medium text-gray-700 mb-2">新密码</label>
                            <input type="password" id="new_password" name="new_password" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-2">确认新密码</label>
                            <input type="password" id="confirm_password" name="confirm_password" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                    </div>
                </div>
                
                <!-- 提交按钮 -->
                <div class="flex justify-end space-x-4 mt-8">
                    <button type="button" onclick="resetForm()" 
                            class="px-6 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500">
                        重置
                    </button>
                    <button type="submit" 
                            class="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                        <i class="fas fa-save mr-2"></i>保存修改
                    </button>
                </div>
            </form>
        </div>
        
        <!-- 预览区域 -->
        <div class="bg-white shadow-md rounded-lg p-6">
            <h3 class="text-lg font-semibold mb-4">个人信息预览</h3>
            <div class="flex items-start space-x-4">
                <div id="avatarPreview" class="w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center">
                    <i class="fas fa-user text-2xl text-gray-400"></i>
                </div>
                <div>
                    <h4 id="namePreview" class="text-xl font-semibold text-gray-800">未设置姓名</h4>
                    <p id="usernamePreview" class="text-gray-600">@未设置用户名</p>
                    <p id="emailPreview" class="text-gray-600 text-sm">未设置邮箱</p>
                    <p id="phonePreview" class="text-gray-600 text-sm">未设置电话</p>
                    <p id="bioPreview" class="text-gray-700 mt-2">未设置个人简介</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 侧边栏切换功能
        const sidebarToggle = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebarOverlay');

        function toggleSidebar() {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('opacity-0');
            sidebarOverlay.classList.toggle('pointer-events-none');
        }

        function closeSidebar() {
            sidebar.classList.add('-translate-x-full');
            sidebarOverlay.classList.add('opacity-0');
            sidebarOverlay.classList.add('pointer-events-none');
        }

        sidebarToggle.addEventListener('click', toggleSidebar);
        sidebarOverlay.addEventListener('click', closeSidebar);

        // 检查用户登录状态
        function checkAuthStatus() {
            const token = localStorage.getItem('access_token');
            const user = JSON.parse(localStorage.getItem('user') || '{}');
            const userControls = document.getElementById('userControls');
            
            if (token) {
                userControls.innerHTML = `
                    <a href="/profile" class="text-blue-500 hover:text-blue-700">
                        <i class="fas fa-user mr-1"></i>个人信息
                    </a>
                    <span class="text-gray-700">欢迎, ${user.username}</span>
                    <button onclick="logout()" class="text-red-500 hover:text-red-700">
                        <i class="fas fa-sign-out-alt mr-1"></i>退出
                    </button>
                `;
            } else {
                window.location.href = '/login';
            }
        }
        
        // 退出登录
        function logout() {
            localStorage.removeItem('access_token');
            localStorage.removeItem('user');
            window.location.href = '/login';
        }
        
        // 显示警告消息
        function showAlert(message, type) {
            const alertDiv = document.getElementById('alert');
            alertDiv.className = `mb-4 p-4 rounded-md ${type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`;
            alertDiv.textContent = message;
            alertDiv.classList.remove('hidden');
            
            setTimeout(() => {
                alertDiv.classList.add('hidden');
            }, 3000);
        }
        
        // 加载用户信息
        async function loadUserProfile() {
            const token = localStorage.getItem('access_token');
            if (!token) {
                window.location.href = '/login';
                return;
            }
            
            try {
                const response = await fetch('/api/user/profile', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const user = await response.json();
                    populateForm(user);
                    updatePreview(user);
                } else {
                    showAlert('获取用户信息失败', 'error');
                }
            } catch (error) {
                showAlert('网络错误', 'error');
            }
        }
        
        // 填充表单
        function populateForm(user) {
            document.getElementById('username').value = user.username || '';
            document.getElementById('email').value = user.email || '';
            document.getElementById('full_name').value = user.full_name || '';
            document.getElementById('phone').value = user.phone || '';
            document.getElementById('avatar_url').value = user.avatar_url || '';
            document.getElementById('bio').value = user.bio || '';
        }
        
        // 更新预览
        function updatePreview(user) {
            document.getElementById('namePreview').textContent = user.full_name || '未设置姓名';
            document.getElementById('usernamePreview').textContent = `@${user.username || '未设置用户名'}`;
            document.getElementById('emailPreview').textContent = user.email || '未设置邮箱';
            document.getElementById('phonePreview').textContent = user.phone || '未设置电话';
            document.getElementById('bioPreview').textContent = user.bio || '未设置个人简介';
            
            // 更新头像预览
            const avatarPreview = document.getElementById('avatarPreview');
            if (user.avatar_url) {
                avatarPreview.innerHTML = `<img src="${user.avatar_url}" alt="头像" class="w-20 h-20 rounded-full object-cover">`;
            } else {
                avatarPreview.innerHTML = '<i class="fas fa-user text-2xl text-gray-400"></i>';
            }
        }
        
        // 表单提交处理
        document.getElementById('profileForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const token = localStorage.getItem('access_token');
            if (!token) {
                showAlert('请先登录', 'error');
                return;
            }
            
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            
            // 分离基本信息和密码信息
            const profileData = {
                email: data.email,
                full_name: data.full_name,
                phone: data.phone,
                avatar_url: data.avatar_url,
                bio: data.bio
            };
            
            const passwordData = {
                current_password: data.current_password,
                new_password: data.new_password,
                confirm_password: data.confirm_password
            };
            
            try {
                // 先更新基本信息
                const profileResponse = await fetch('/api/user/profile', {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(profileData)
                });
                
                const profileResult = await profileResponse.json();
                
                if (!profileResponse.ok) {
                    showAlert(profileResult.message || '基本信息更新失败', 'error');
                    return;
                }
                
                // 如果需要修改密码
                if (passwordData.new_password || passwordData.confirm_password) {
                    if (!passwordData.current_password) {
                        showAlert('请输入当前密码', 'error');
                        return;
                    }
                    if (passwordData.new_password !== passwordData.confirm_password) {
                        showAlert('新密码与确认密码不一致', 'error');
                        return;
                    }
                    if (passwordData.new_password.length < 6) {
                        showAlert('新密码长度至少6位', 'error');
                        return;
                    }
                    
                    // 修改密码
                    const passwordResponse = await fetch('/api/user/change-password', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            current_password: passwordData.current_password,
                            new_password: passwordData.new_password
                        })
                    });
                    
                    const passwordResult = await passwordResponse.json();
                    
                    if (!passwordResponse.ok) {
                        showAlert(passwordResult.message || '密码修改失败', 'error');
                        return;
                    }
                    
                    // 清空密码字段
                    document.getElementById('current_password').value = '';
                    document.getElementById('new_password').value = '';
                    document.getElementById('confirm_password').value = '';
                    
                    showAlert('个人信息和密码更新成功', 'success');
                } else {
                    showAlert('个人信息更新成功', 'success');
                }
                
                // 更新预览
                updatePreview(profileResult.user);
                
            } catch (error) {
                showAlert('网络错误', 'error');
            }
        });
        
        // 重置表单
        function resetForm() {
            loadUserProfile();
            document.getElementById('current_password').value = '';
            document.getElementById('new_password').value = '';
            document.getElementById('confirm_password').value = '';
        }
        
        // 实时预览
        document.getElementById('avatar_url').addEventListener('input', (e) => {
            const url = e.target.value;
            const avatarPreview = document.getElementById('avatarPreview');
            if (url) {
                avatarPreview.innerHTML = `<img src="${url}" alt="头像" class="w-20 h-20 rounded-full object-cover" onerror="this.outerHTML='<i class=\\'fas fa-user text-2xl text-gray-400\\'></i>'">`;
            } else {
                avatarPreview.innerHTML = '<i class="fas fa-user text-2xl text-gray-400"></i>';
            }
        });
        
        document.getElementById('full_name').addEventListener('input', (e) => {
            document.getElementById('namePreview').textContent = e.target.value || '未设置姓名';
        });
        
        document.getElementById('email').addEventListener('input', (e) => {
            document.getElementById('emailPreview').textContent = e.target.value || '未设置邮箱';
        });
        
        document.getElementById('phone').addEventListener('input', (e) => {
            document.getElementById('phonePreview').textContent = e.target.value || '未设置电话';
        });
        
        document.getElementById('bio').addEventListener('input', (e) => {
            document.getElementById('bioPreview').textContent = e.target.value || '未设置个人简介';
        });
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            checkAuthStatus();
            loadUserProfile();
        });
    </script>
</body>

</html>